<template>
  <div class="q-pb-md">
    <div class="row">
      <q-btn
        :label="show ? '隐藏查询' : '展开查询'"
        size="sm"
        :icon="show ? 'arrow_drop_up' : 'arrow_drop_down'"
        style="width: calc(100% - 28px)"
        dense
        :color="show ? 'grey-6' : 'grey-9'"
        @click="show = !show"
      />
      <q-space />
      <q-btn icon="settings" color="grey-10" dense size="sm" @click="pop = true">
        <q-badge v-if="queryConfig.value" color="red" floating rounded></q-badge>
        <q-tooltip>配置</q-tooltip>
      </q-btn>
    </div>
    <q-slide-transition>
      <q-card class="row" v-show="show">
        <div :class="colClass" v-for="(field, idx ) in queryFieldList" :key="idx">
          <dateRangeInput v-if="field.type === 'date' && (field.single === undefined || !field.single)" :field="field" :ref="field.name" />
          <dateInput v-if="field.type === 'date' && field.single" :field="field" :ref="field.name" />
          <fieldInput v-if="field.type === 'input'" :field="field" debounce="500" :ref="field.name" />
          <filterSelect v-if="field.type === 'select'" :field="field" input-debounce="500" :name="field.name" />
          <monthrangeinput v-if="field.type === 'month' && !field.single" :field="field" :ref="field.name" />
          <monthinput v-if="field.type === 'month' && field.single" :field="field" :ref="field.name" />
          <yearrangeinput v-if="field.type === 'year'" :field="field" :ref="field.name" />
          <scopeinput v-if="field.type === 'scope'" :field="field" :ref="field.name" />
          <fieldToggle v-if="field.type === 'toggle'" :field="field" :ref="field.name" />
          <autocomplete v-if="field.type === 'autocomplete'" :field="field" input-debounce="500" :ref="field.name" />
          <treeselect v-if="field.type === 'treeSelect'" :field="field" input-debounce="500" :ref="field.name" />
        </div>
        <div :class="colClass">
          <q-btn label="重置" icon="settings_backup_restore" flat @click="reset" :size="btnSize">
            <q-tooltip>重置查询条件</q-tooltip>
          </q-btn>
          <q-btn label="查询" color="secondary" icon="search" @click="$emit('search')" :size="btnSize">
            <q-tooltip>查询数据</q-tooltip>
          </q-btn>
        </div>
      </q-card>
    </q-slide-transition>

    <q-dialog v-model="pop">
      <q-card style="width: 650px;">
        <q-bar>
          <div>配置查询</div>

          <q-space />

          <q-btn dense flat icon="close" v-close-popup>
            <q-tooltip>关闭</q-tooltip>
          </q-btn>
        </q-bar>

        <q-card-section >
          <div class="text-h6">1.显示/隐藏 查询字段</div>
          <transferBox style="height: 300px" :field="queryConfig" @change="saveQuery"></transferBox>
          <q-separator class="q-my-md" />
          <q-banner inline-actions rounded>
            <div class="text-h6">2.将当前查询条件设置为默认</div>
            <div class="text-weight-light">打开页面时，默认按此条件检索数据</div>
            <template v-slot:action>
              <q-btn label="设置" dense flat icon="save" color="primary" @click="setDefault"></q-btn>
              <q-btn label="清除" dense flat icon="cleaning_services" color="secondary" @click="clearDefault"></q-btn>
            </template>
          </q-banner>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import fieldInput from 'src/components/FieldInput.vue';
import filterSelect from 'src/components/FilterSelect.vue';
import dateRangeInput from 'src/components/DateRangeInput.vue';
import dateInput from 'src/components/DateInput.vue';
import monthrangeinput from 'src/components/MonthRangeInput.vue';
import monthinput from 'src/components/MonthInput.vue';
import yearrangeinput from 'src/components/YearRangeInput.vue';
import scopeinput from 'src/components/ScopeInput.vue';
import autocomplete from 'src/components/Autocomplete.vue';
import treeselect from 'src/components/FieldTreeSelect.vue';
import transferBox from 'src/components/TransferBox.vue';
import fieldToggle from 'src/components/FieldToggle.vue';

export default defineComponent({
  components: {
    fieldInput,
    filterSelect,
    dateRangeInput,
    monthrangeinput,
    monthinput,
    yearrangeinput,
    scopeinput,
    autocomplete,
    treeselect,
    transferBox,
    dateInput,
    fieldToggle
  },
  name: 'searchArea',
  props: {
    fieldlist: {
      type: Object,
      default: () => {}
    },
    btnSize: {
      type: String,
      default: 'md'
    },
    id: {
      type: String,
      default: ''
    }
  },
  emits: ['reset', 'search'],
  data () {
    return {
      show: true,
      pop: false,
      queryConfig: {
        label: '',
        value: '',
        options: [],
        leftLabel: '显示字段',
        rightLabel: '隐藏字段'
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      if (this.$q.screen.xs) {
        this.show = false;
      } else if (this.$q.localStorage.has(`${this.pageKeyWord}SearchShow`)) {
        this.show = this.$q.localStorage.getItem(`${this.pageKeyWord}SearchShow`);
      }
    });

    const options = [];
    for (const key in this.fieldlist) {
      if (this.fieldlist[key].type) {
        this.fieldlist[key].name = key;

        options.push({
          value: key,
          label: this.fieldlist[key].label
        });
      }
    }
    // 显示字段
    let value = '';
    if (this.$q.localStorage.has(`${this.pageKeyWord}Query`)) {
      value = this.$q.localStorage.getItem(`${this.pageKeyWord}Query`);
    } else {
      value = Object.keys(this.fieldlist).filter(v => this.fieldlist[v].hide).join(',');
    }

    this.queryConfig.options = options;
    this.queryConfig.value = value;

    // 加载默认条件值
    if (this.$q.localStorage.has(`${this.pageKeyWord}Default`)) {
      const valDefault = this.$q.localStorage.getItem(`${this.pageKeyWord}Default`);
      for (const key in valDefault) {
        if (this.fieldlist[key]) {
          this.fieldlist[key].value = valDefault[key];
        }
      }
    }
  },
  methods: {
    reset () {
      for (const field in this.fieldlist) {
        if (this.fieldlist[field].default !== undefined) {
          this.fieldlist[field].value = this.fieldlist[field].default;
        } else {
          if (this.fieldlist[field].type === 'date') {
            if (this.$refs[field] && this.$refs[field].length > 0) {
              for (const component of this.$refs[field]) {
                component.init();
              }
            }
          } else {
            this.fieldlist[field].value = this.fieldlist[field].type == 'toggle' ? false : '';
          }
        }
      }
      this.$emit('reset');
    },
    toggle (show) {
      if (show === null || show === undefined) {
        this.show = !this.show;
      } else {
        this.show = !!show;
      }
    },
    saveQuery (data) {
      const { newValue } = data;
      this.$q.localStorage.set(`${this.pageKeyWord}Query`, newValue);
    },
    setDefault () {
      const valDefault = {};
      for (const key in this.fieldlist) {
        if (this.fieldlist[key].value) {
          valDefault[key] = this.fieldlist[key].value;
        }
      }
      this.$q.localStorage.set(`${this.pageKeyWord}Default`, valDefault);
    },
    clearDefault () {
      this.$q.localStorage.remove(`${this.pageKeyWord}Default`);
    }
  },
  computed: {
    colClass () {
      let cls;
      switch (Object.keys(this.fieldlist).length) {
        case 1:
          cls = ['col-lg-6', 'col-sm-6', 'col-xs-12', 'q-pa-sm'];
          break;
        case 2:
          cls = ['col-lg-4', 'col-sm-4', 'col-xs-12', 'q-pa-sm'];
          break;
        default:
          cls = ['col-lg-3', 'col-sm-4', 'col-xs-12', 'q-pa-sm'];
      }
      return cls;
    },
    pageKeyWord () {
      const path = this.$route.path.split('/');
      const key = path.length > 2 ? this.$route.path.split('/')[2] : '';
      return key + this.id;
    },
    queryFieldList () {
      const hideArr = this.queryConfig.value.split(',');
      const list = {};
      for (const key in this.fieldlist) {
        if (hideArr.includes(key) || !this.fieldlist[key].type) continue;

        list[key] = this.fieldlist[key];
      }
      return list;
    }
  },
  watch: {
    show (val) {
      this.$q.localStorage.set(`${this.pageKeyWord}SearchShow`, val);
    }
  }
});
</script>
